package com.moleq.device;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Handler;
import android.os.Message;

import com.moleq.enums.PaymentType;
import com.moleq.enums.TransactionType;
import com.moleq.util.ImageUtil;
import com.moleq.util.StringUtils;
import com.pax.poslink.CommSetting;
import com.pax.poslink.ManageRequest;
import com.pax.poslink.ManageResponse;
import com.pax.poslink.PaymentRequest;
import com.pax.poslink.PaymentResponse;
import com.pax.poslink.PosLink;
import com.pax.poslink.ProcessTransResult;
import com.pax.poslink.ProcessTransResult.ProcessTransResultCode;

public class PaxPinPad extends BasePinPad {

	private static final String TAG = "PAXPosMachine";

	private static final String PPP_TRANS_UNKNOW = "UNKNOWN";
	private static final String PPP_TRANS_AUTH = "AUTH";
	private static final String PPP_TRANS_SALE = "SALE";
	private static final String PPP_TRANS_RETURN = "RETURN";
	private static final String PPP_TRANS_VOID = "VOID";
	private static final String PPP_TRANS_POSTAUTH = "POSTAUTH";
	private static final String PPP_TRANS_FORCEAUTH = "FORCEAUTH";
	private static final String PPP_TRANS_ADJUST = "ADJUST";
	private static final String PPP_TRANS_INQUIRY = "INQUIRY";
	private static final String PPP_TRANS_ACTIVATE = "ACTIVATE";
	private static final String PPP_TRANS_DEACTIVATE = "DEACTIVATE";
	private static final String PPP_TRANS_RELOAD = "RELOAD";
	private static final String PPP_TRANS_VOID_SALE = "VOID SALE";
	private static final String PPP_TRANS_VOID_RETURN = "VOID RETURN";
	private static final String PPP_TRANS_VOID_AUTH = "VOID AUTH";
	private static final String PPP_TRANS_VOID_POSTAUTH = "VOID POSTAUTH";
	private static final String PPP_TRANS_VOID_FORCEAUTH = "VOID FORCEAUTH";
	private static final String PPP_TRANS_VOID_WITHDRAWAL = "VOID WITHDRAWAL";
	private static final String PPP_TRANS_REVERSAL = "REVERSAL";
	private static final String PPP_TRANS_WITHDRAWAL = "WITHDRAWAL";
	private static final String PPP_TRANS_ISSUE = "ISSUE";
	private static final String PPP_TRANS_CASHOUT = "CASHOUT";
	private static final String PPP_TRANS_REPLACE = "REPLACE";
	private static final String PPP_TRANS_MERGE = "MERGE";
	private static final String PPP_TRANS_REPORTLOST = "REPORTLOST";
	private static final String PPP_TRANS_REDEEM = "REDEEM";
	private static final String PPP_TRANS_VERIFY = "VERIFY";

	private static final String PPP_TENDER_CREDIT = "CREDIT";
	private static final String PPP_TENDER_DEBIT = "DEBIT";
	private static final String PPP_TENDER_CHECK = "CHECK";
	private static final String PPP_TENDER_EBT_FOODSTAMP = "EBT_FOODSTAMP";
	private static final String PPP_TENDER_EBT_CASHBENEFIT = "EBT_CASHBENEFIT";
	private static final String PPP_TENDER_GIFT = "GIFT";
	private static final String PPP_TENDER_LOYALTY = "LOYALTY";
	private static final String PPP_TENDER_CASH = "CASH";

	private static final String PPP_COMM_UART = "UART";
	private static final String PPP_COMM_TCP = "TCP";

//	protected static final int TRANSACTION_SUCCESSED = 100;
//
//	protected static final int TRANSACTION_TIMEOUT = 101;
//
//	protected static final int TRANSACTION_FAILURE = 102;

	private static final String MESSAGE_CODE = "message_code";

	private static final String MESSAGE_DESC = "message_description";

	// manage trans
	public static String MGR_TRANS_INIT = "INIT";
	public static String MGR_TRANS_GETVAR = "GETVAR";
	public static String MGR_TRANS_SETVAR = "SETVAR";
	public static String MGR_TRANS_SHOWDIALOG = "SHOWDIALOG";
	public static String MGR_TRANS_GETSIGNATURE = "GETSIGNATURE";
	public static String MGR_TRANS_SHOWMESSAGE = "SHOWMESSAGE";
	public static String MGR_TRANS_CLEARMESSAGE = "CLEARMESSAGE";
	public static String MGR_TRANS_CLEARSCREEN = "CLEARSCREEN";
	public static String MGR_TRANS_RESET = "RESET";
	public static String MGR_TRANS_UPDATEIMAGE = "UPDATEIMAGE";
	public static String MGR_TRANS_DOSIGNATURE = "DOSIGNATURE";
	public static String MGR_TRANS_DELETEIMAGE = "DELETEIMAGE";

	// manage edc
	public static String MGR_EDC_ALL = "ALL";
	public static String MGR_EDC_CREDIT = "CREDIT";
	public static String MGR_EDC_DEBIT = "DEBIT";
	public static String MGR_EDC_CHECK = "CHECK ";
	public static String MGR_EDC_EBT_FOODSTAMP = "EBT_FOODSTAMP";
	public static String MGR_EDC_EBT_CASHBENEFIT = "EBT_CASHBENEFIT";
	public static String MGR_EDC_GIFT = "GIFT";
	public static String MGR_EDC_LOYALTY = "LOYALTY";
	public static String MGR_EDC_CASH = "CASH";

	// Result Code
	private static final String ERROR_CODE_000000 = "000000";
	private static final String ERROR_CODE_000100 = "000100";
	private static final String ERROR_CODE_100001 = "100001";
	private static final String ERROR_CODE_100002 = "100002";
	private static final String ERROR_CODE_100003 = "100003";
	private static final String ERROR_CODE_100004 = "100004";
	private static final String ERROR_CODE_100005 = "100005";
	private static final Object ERROR_CODE_100010 = "100010";
	private static final String ERROR_CODE_100011 = "100011";
	private static final Object ERROR_CODE_100019 = "100019";
	private static final String ERROR_CODE_199999 = "199999";
	private static final String ERROR_CODE_200000 = "200000";

	// error message
	private static final String ERROR_MSG_OK = "OK";
	private static final String ERROR_MSG_DECLINE = "DECLINE";
	private static final String ERROR_MSG_ABORTED = "ABORTED";
	private static final String ERROR_MSG_TIMEOUT = "TIMEOUT";
	private static final String ERROR_MSG_DUP_TRANSACTION = "DUP TRANSACTION";
	private static final String ERROR_TERMINAL_ERROR = "TERMINAL ERROR";
	private static final String ERROR_MSG_TRACK_INVALID = "TRACK INVALID";
	private static final String ERROR_MSG_SWIPE_ERROR = "SWIPE ERROR";
	private static final Object ERROR_MSG_COMM_ERROR = "COMM ERROR";

//	private PosLink poslink = new PosLink();
	public String refNo = "";
	public PaymentType tenderType;
	public TransactionType transType;
	public String mAppDataFolder;
	private String[] mCommType = { "UART", "TCP" };
	private String[] mTenders = { "CREDIT", "DEBIT", "CHECK", "EBT_FOODSTAMP", "EBT_CASHBENEFIT", "GIFT", "LOYALTY", "CASH" };
	private String[] mTrans = { "UNKNOWN", "AUTH", "SALE", "RETURN", "VOID", "POSTAUTH", "FORCEAUTH", "ADJUST", "INQUIRY", "ACTIVATE", "DEACTIVATE", "RELOAD", "VOID SALE", "VOID RETURN", "VOID AUTH", "VOID POSTAUTH", "VOID FORCEAUTH", "VOID WITHDRAWAL", "REVERSAL", "WITHDRAWAL", "ISSUE", "CASHOUT", "REPLACE", "MERGE", "REPORTLOST", "REDEEM", "VERIFY" };

	public PaxPinPad(String absoluteDir) {
		mAppDataFolder = absoluteDir;

	}

	private String ParseTransactionType(TransactionType transType) {
		String result = "";

		switch (transType) {

		case UNKNOWN:
			result = this.mTrans[0];
			break;
		case AUTH:
			result = this.mTrans[1];
			break;
		case SALE:
			result = this.mTrans[2];
			break;
		case RETURN:
			result = this.mTrans[3];
			break;
		case VOID:
			result = this.mTrans[4];
			break;
		case POSTAUTH:
			result = this.mTrans[5];
			break;
		}

		return result;
	}

	private String ParsePaymentType(PaymentType tenderType) {
		String result = "";
		switch (tenderType) {
		case CASH:
			result = mTenders[7];
			break;
		case CHECK:
			result = mTenders[2];
			break;
		case CREDIT_CARD:
			result = mTenders[0];
			break;
		case DEBIT_CARD:
			result = mTenders[1];
			break;
		case EBT_CASH:
			result = mTenders[4];
			break;
		case FOOD_STAMP:
			result = mTenders[3];
			break;
		case GIFT_CARD:
			result = mTenders[5];
			break;
		case GIFT_CERTIFICATE:
			//
			break;
		case STORE_CREDIT:
			//
			break;
		case VOICE_AUTH:
			//
			break;
		case VOUCHER:
			//
			break;
		}
		return result;
	}

	private String getEDCTypeByPaymentType(PaymentType tenderType) {
		String result = "";
		switch (tenderType) {
		case CASH:
			result = PaxPinPad.MGR_EDC_CASH;
			break;
		case CHECK:
			result = PaxPinPad.MGR_EDC_CHECK;
			break;
		case CREDIT_CARD:
			result = PaxPinPad.MGR_EDC_CREDIT;
			break;
		case DEBIT_CARD:
			result = PaxPinPad.MGR_EDC_DEBIT;
			break;
		case EBT_CASH:
			result = PaxPinPad.MGR_EDC_EBT_CASHBENEFIT;
			break;
		case FOOD_STAMP:
			result = PaxPinPad.MGR_EDC_EBT_FOODSTAMP;
			break;
		case GIFT_CARD:
			result = PaxPinPad.MGR_EDC_GIFT;
			break;
		case GIFT_CERTIFICATE:
			//
			break;
		case STORE_CREDIT:
			//
			break;
		case VOICE_AUTH:
			//
			break;
		case VOUCHER:
			//
			break;
		}
		return result;
	}

	@Override
	public void ProcessPayment() {

		new Thread(new Runnable() {
			public void run() {
//				mPaymentResponse = new MPaymentResponse();
//				if (poslink != null) {
				PosLink  poslink = new PosLink();
					PaymentRequest payrequest = new PaymentRequest();
					setPaymentRequest(payrequest);
					
					poslink.appDataFolder = mPaymentRequest.appDataFolder;
					poslink.PaymentRequest = payrequest;
					poslink.ManageRequest  = null;

					ProcessTransResult ptr = poslink.ProcessTrans();

					if (ptr.Code == ProcessTransResultCode.OK) {
						PaymentResponse response = poslink.PaymentResponse;
						
						setPaymentResponse(response);
						

						if (mPaymentResponse.ResultType.equals(BasePinPad.RESULT_OK)) {
//							reset();
							isForce = false;
							currentDupTransCount = 0;
						} else if (mPaymentResponse.ResultType.equals(BasePinPad.RESULT_DUPLICATE_TRANSACTION)) {
							currentDupTransCount++;

							if (currentDupTransCount > invalidDupTransCount) {
								isForce = true;
							}
						}
						Message msg = new Message();
						msg.what = BasePinPad.PAYMENT_SUCCEED;
						msg.obj = mPaymentResponse;
						mPaxPinPadHandler.sendMessage(msg);

					} else if (ptr.Code == ProcessTransResultCode.TimeOut) {
						Message msg = new Message();
						msg.what = BasePinPad.PAYMENT_TIMEOUT;
						msg.obj = mPaymentResponse;
						mPaxPinPadHandler.sendMessage(msg);

					} else {
						mPaymentResponse.ResultType = RESULT_TERMINAL_ERROR;
						mPaymentResponse.ResultCode = ERROR_CODE_199999;
						mPaymentResponse.ResultTxt = ERROR_TERMINAL_ERROR;

						Message msg = new Message();
						msg.what = BasePinPad.PAYMENT_FAILED;
						msg.obj = mPaymentResponse;
						mPaxPinPadHandler.sendMessage(msg);

					}
				} 
//				else {
//					mPaymentResponse.ResultType = RESULT_TERMINAL_ERROR;
//					mPaymentResponse.ResultCode = ERROR_CODE_199999;
//					mPaymentResponse.ResultTxt = ERROR_TERMINAL_ERROR;
//
//					Message msg = new Message();
//					msg.what = BasePinPad.PAYMENT_FAILED;
//					msg.obj = mPaymentResponse;
//					mPaxPinPadHandler.sendMessage(msg);
//
//				}

//			}

			
		}).start();

	}

	@Override
	public void onDisconnect() {
//		if (poslink != null) {
//			poslink = null;
//			mIsConnected = false;
//		}
		
		mIsConnected = false;
	}

	@Override
	public void onConnect() {

//		if (poslink == null) {
//			poslink = new PosLink();
//		}

		// CommSetting commset = new CommSetting();
		CommSetting commset = new CommSetting(mAppDataFolder);

		if (mPinPadSetting == null) {
			mIsConnected = false;
			mIsEnable = false;
		} else {
//			commset.CommType = mCommType[0];
			commset.CommType = mPinPadSetting.getCon_type();
			commset.TimeOut = String.valueOf(mPinPadSetting.getTimeOut());
			commset.SerialPort = ParseProt(mPinPadSetting.getSerialPort());
			commset.DestIP = mPinPadSetting.getDestIP();
			commset.DestPort = mPinPadSetting.getDestPort();

			// poslink.CommSetting = commset;
			commset.SaveCommSettingFile();

			mIsEnable = true;
			mIsConnected = true;
		}

	}

	private String ParseProt(int port) {

		String result = "";
		switch (port) {
		case 1:
			result = "COM1";
			break;
		case 2:
			result = "COM2";
			break;
		case 3:
			result = "COM3";
			break;
		case 4:
			result = "COM4";
			break;
		case 5:
			result = "COM5";
			break;

		}
		return result;
	}

	@Override
	public void doSignature() {
		mPaymentRequest.ActionType = PaxPinPad.MGR_TRANS_DOSIGNATURE;
		new Thread(new Runnable() {
			public void run() {

				// ActionID = BasePinPad.PROCESS_PINPAD_DOSIGNATURE;
				ManageRequest request = new ManageRequest();
				setManageRequest(request);
				
				request.Upload = 0;
				
				PosLink  poslink = new PosLink();
//				mPaymentResponse = new MPaymentResponse();
//				if (poslink != null) {
					// set the folder whereto read the "comsetting.ini" file
					poslink.appDataFolder = mAppDataFolder;
					poslink.PaymentRequest = null;
					poslink.ManageRequest = request;
					ProcessTransResult ptr = poslink.ProcessTrans();

					// transaction successful
					if (ptr.Code == ProcessTransResultCode.OK) {
						// ManageResponse is the result of the manage
						// transaction to the
						// server.
						ManageResponse response = poslink.ManageResponse;
						mPaymentResponse.ResultType = parseResponse(response.ResultCode, response.ResultTxt);
						mPaymentResponse.ResultCode = response.ResultCode;
						mPaymentResponse.ResultTxt = response.ResultTxt;

						if (mPaymentResponse.ResultType.equals(BasePinPad.RESULT_OK)) {
							
							Message msg = new Message();
							msg.what = BasePinPad.DOSIGNATURE_SUCCEED;
							msg.obj = mPaymentResponse;
							mPaxPinPadHandler.sendMessage(msg);

						} else {

							Message msg = new Message();
							msg.what = BasePinPad.DOSIGNATURE_FAILED;
							msg.obj = mPaymentResponse;
							mPaxPinPadHandler.sendMessage(msg);
						}
					} else if (ptr.Code == ProcessTransResultCode.TimeOut) {

						Message msg = new Message();
						msg.what = BasePinPad.DOSIGNATURE_TIMEOUT;
						msg.obj = mPaymentResponse;
						mPaxPinPadHandler.sendMessage(msg);

					} else {
						mPaymentResponse.ResultType = RESULT_TERMINAL_ERROR;
						mPaymentResponse.ResultCode = ERROR_CODE_199999;
						mPaymentResponse.ResultTxt = "Do signature transaction faild.";

						Message msg = new Message();
						msg.what = BasePinPad.DOSIGNATURE_FAILED;
						msg.obj = mPaymentResponse;
						mPaxPinPadHandler.sendMessage(msg);

					}
				} 
//			else {
//					mPaymentResponse.ResultType = RESULT_TERMINAL_ERROR;
//					mPaymentResponse.ResultCode = ERROR_CODE_199999;
//					mPaymentResponse.ResultTxt = ERROR_TERMINAL_ERROR;
//
//					Message msg = new Message();
//					msg.what = BasePinPad.DOSIGNATURE_FAILED;
//					msg.obj = mPaymentResponse;
//					mPaxPinPadHandler.sendMessage(msg);
//				}
//
//			}
		}).start();

	}

	@Override
	public void getSignature() {

       mPaymentRequest.ActionType = PaxPinPad.MGR_TRANS_GETSIGNATURE;
		new Thread(new Runnable() {
			public void run() {
				
//			 sleep(10000);
				
				ManageRequest mgrequest = new ManageRequest();

				setManageRequest(mgrequest);
				
				mgrequest.TransType = mgrequest.ParseTransType("GETSIGNATURE");
				mgrequest.EDCType = mgrequest.ParseEDCType("ALL") ;
				mgrequest.Upload = 0;
				mgrequest.TimeOut ="900";
				mgrequest.HRefNum = "";

//				if (poslink != null) {
				PosLink  poslink = new PosLink();
					// set the folder whereto read the "comsetting.ini" file
					poslink.appDataFolder = mAppDataFolder;
					poslink.PaymentRequest = null;
					poslink.ManageRequest = mgrequest;
					ProcessTransResult ptr = poslink.ProcessTrans();

					// transaction successful
					if (ptr.Code == ProcessTransResultCode.OK) {
						// ManageResponse is the result of the manage
						// transaction to the
						// server.
						ManageResponse response = poslink.ManageResponse;
						mPaymentResponse.ResultType = parseResponse(response.ResultCode, response.ResultTxt);
						mPaymentResponse.ResultCode = response.ResultCode;
						mPaymentResponse.ResultTxt = response.ResultTxt;
						
						mPaymentResponse.ResultSignature = "";

						if (mPaymentResponse.ResultType.equals(BasePinPad.RESULT_OK)) {

							String path = response.SigFileName;

							if (path == null || path.equals("")) {
								mPaymentResponse.ResultCode = ERROR_CODE_199999;
								mPaymentResponse.ResultTxt = "signature file path is null";
								mPaymentResponse.ResultSignature = "signature file path is null";
								
								Message msg = new Message();
								msg.what = BasePinPad.GETSIGNATURE_FAILED;
								msg.obj = mPaymentResponse;
								mPaxPinPadHandler.sendMessage(msg);
							} else {

								mPaymentResponse.ResultSignature = getSignatureBmpString(path);

								Message msg = new Message();
								msg.what = BasePinPad.GETSIGNATURE_SUCCEED;
								msg.obj = mPaymentResponse;
								mPaxPinPadHandler.sendMessage(msg);
							}

						} else {
							Message msg = new Message();
							msg.what = BasePinPad.GETSIGNATURE_FAILED;
							msg.obj = mPaymentResponse;
							mPaxPinPadHandler.sendMessage(msg);
						}
					} else if (ptr.Code == ProcessTransResultCode.TimeOut) {

						Message msg = new Message();
						msg.what = BasePinPad.GETSIGNATURE_TIMEOUT;
						msg.obj = mPaymentResponse;
						mPaxPinPadHandler.sendMessage(msg);
						// mSignatureListener.onError(BasePinPad.DOSIGNATURE_TIMEOUT,
						// "");
					} else {
						mPaymentResponse.ResultType = RESULT_TERMINAL_ERROR;
						mPaymentResponse.ResultCode = ERROR_CODE_199999;
						mPaymentResponse.ResultTxt = "Get signature transaction faild.";

						Message msg = new Message();
						msg.what = BasePinPad.GETSIGNATURE_FAILED;
						msg.obj = mPaymentResponse;
						mPaxPinPadHandler.sendMessage(msg);

					}
				} 
//				else {
//					mPaymentResponse.ResultType = RESULT_TERMINAL_ERROR;
//					mPaymentResponse.ResultCode = ERROR_CODE_199999;
//					mPaymentResponse.ResultTxt = ERROR_TERMINAL_ERROR;
//
//					Message msg = new Message();
//					msg.what = BasePinPad.GETSIGNATURE_FAILED;
//					msg.obj = mPaymentResponse;
//					mPaxPinPadHandler.sendMessage(msg);
//				}
//
//			}

			
		}).start();

	}
	
//	
//	private Handler mManageHandler = new Handler(){
//		@Override
//		public void handleMessage(Message msg) {
//			switch (msg.what) {
//				case BasePinPad.TRANSACTION_SUCCESSED:
//					//
//					break;
//				case BasePinPad.TRANSACTION_TIMEOUT:
//				case BasePinPad.TRANSACTION_FAILURE:
//					
//			}
//			
//		}
//	};

	private Handler mPaxPinPadHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			MPaymentResponse response = null;
			switch (msg.what) {
			case BasePinPad.TRANSACTION_SUCCESSED:
			case BasePinPad.TRANSACTION_TIMEOUT:
			case BasePinPad.TRANSACTION_FAILURE:
				//
				break;

			case BasePinPad.PAYMENT_TIMEOUT:
				mListener.onTimeOutEvent();
				break;
			case BasePinPad.PAYMENT_FAILED:
			case BasePinPad.PAYMENT_SUCCEED:
				response = (MPaymentResponse) msg.obj;
				mListener.onEventResponse(msg.what, response);
				break;
			case BasePinPad.GETSIGNATURE_TIMEOUT:
			case BasePinPad.DOSIGNATURE_TIMEOUT:
				response = (MPaymentResponse) msg.obj;
				mSignatureListener.onError(msg.what, response);
				break;
			case BasePinPad.GETSIGNATURE_FAILED:
			case BasePinPad.DOSIGNATURE_FAILED:
				response = (MPaymentResponse) msg.obj;
				mSignatureListener.onError(msg.what, response);
				break;
			case BasePinPad.DOSIGNATURE_SUCCEED:
				response = (MPaymentResponse) msg.obj;
				mSignatureListener.onDoSignature(msg.what, response);
				break;

			case BasePinPad.GETSIGNATURE_SUCCEED:
				response = (MPaymentResponse) msg.obj;
				mSignatureListener.onGetSignature(msg.what, response);
				break;
			}
		}
	};

	private String parseResponse(String errorCode, String errorMessage) {
		String result = "";

		if (errorCode.equals(ERROR_CODE_000000)) {
			if (errorMessage.equals(ERROR_MSG_OK)) {
				result = BasePinPad.RESULT_OK;
			}
		} else if (errorCode.equals(ERROR_CODE_000100)) {
			if (errorMessage.equals(ERROR_MSG_DECLINE)) {
				result = BasePinPad.RESULT_DECLINE;
			}
		} else if (errorCode.equals(ERROR_CODE_100001)) {
			if (errorMessage.equals(ERROR_MSG_TIMEOUT)) {
				result = BasePinPad.RESULT_TIMEOUT;
			}
		} else if (errorCode.equals(ERROR_CODE_100002)) {
			if (errorMessage.equals(ERROR_MSG_ABORTED)) {
				result = BasePinPad.RESULT_ABORTED;
			}
		} else if (errorCode.equals(ERROR_CODE_100003)) {

		} else if (errorCode.equals(ERROR_CODE_100004)) {
			//
		} else if (errorCode.equals(ERROR_CODE_100005)) {
			//
		} else if (errorCode.equals(ERROR_CODE_100010)) {
			if (errorMessage.equals(ERROR_MSG_COMM_ERROR)) {
				result = BasePinPad.RESULT_COMM_ERROR;
			}
		} else if (errorCode.equals(ERROR_CODE_100011)) {
			if (errorMessage.equals(ERROR_MSG_DUP_TRANSACTION)) {
				result = BasePinPad.RESULT_DUPLICATE_TRANSACTION;
			}
		} else if (errorCode.equals(ERROR_CODE_100019)) {
			if (errorMessage.equals(ERROR_MSG_TRACK_INVALID)) {
				result = BasePinPad.RESULT_TRACK_INVALID;
			} else if (errorMessage.equals(ERROR_MSG_SWIPE_ERROR)) {
				result = BasePinPad.RESULT_SWIPE_ERROR;
			}
		}

		return result;

	}

	private String getSignatureBmpString(String path) {

		// open file
		File file = new File(path);
		InputStream in = null;
		BufferedReader sr = null;
		String alldata = "";
		try {
			in = new FileInputStream(file);
			sr = new BufferedReader(new InputStreamReader(in));
			String data = "";
			while ((data = sr.readLine()) != null) {
				alldata += data;
				data = "";
				System.out.println(data);
			}
			System.out.println("all =" + alldata);
			// fileView.setText(alldata);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// System.out.println("width  ="+imageView.getWidth());
		// System.out.println("height  ="+imageView.getHeight());

		// show image
		Bitmap bmp = Bitmap.createBitmap(200, 200, Config.ARGB_8888);
		Canvas canvas = new Canvas();
		canvas.setBitmap(bmp);

		String div = "\\^";
		String signature_divide[] = alldata.split(div);
		String x;
		String y;
		String x_y;
		System.out.println("size =" + signature_divide.length);
		for (int i = 0; i < signature_divide.length; i++) {
			try {
				x_y = signature_divide[i];
				int pos = x_y.indexOf(",");
				x = x_y.substring(0, pos);
				y = x_y.substring(pos + 1);

				if (Integer.parseInt(x) <= 480 && Integer.parseInt(y) <= 320)
					bmp.setPixel(Integer.parseInt(x), Integer.parseInt(y), Color.BLACK);

			} catch (Exception e) {
				// e.printStackTrace(); ignore correct point
			}
		}
		
		//connect dots
        Point p1 = new Point();
        Point p2 = new Point();
        Paint blackPen = new Paint();
        blackPen.setColor(Color.BLACK);
        blackPen.setStrokeWidth(2);
        for(int i=1;i<signature_divide.length-1;i++)
        {
        	x_y =  signature_divide[i-1];
        	int pos = signature_divide[i-1].indexOf(",");
        	y = x_y.substring(pos + 1);
			x = x_y.substring(0, pos);
			if(Integer.parseInt(y) == 65535)
				continue;
			p1.x = Integer.parseInt(x);
			p1.y = Integer.parseInt(y);
			
			
			x_y =  signature_divide[i];
        	pos = signature_divide[i].indexOf(",");
        	y = x_y.substring(pos + 1);
			x = x_y.substring(0, pos);
			if(Integer.parseInt(y) == 65535)
				continue;
			p2.x = Integer.parseInt(x);
			p2.y = Integer.parseInt(y);
			
			canvas.drawLine(p1.x, p1.y, p2.x, p2.y, blackPen);
        }

		return ImageUtil.bitmaptoString(bmp);
	}

	private void setManageRequest(ManageRequest mgrequest) {
		mgrequest.TransType = mgrequest.ParseTransType(mPaymentRequest.ActionType);
		mgrequest.EDCType = mgrequest.ParseEDCType(getEDCTypeByPaymentType(mPaymentRequest.PayType));

		mgrequest.TimeOut = "900";
		mgrequest.VarName = "";
		mgrequest.VarValue = "";
		mgrequest.Title = "";
		mgrequest.Button1 = "";
		mgrequest.Button2 = "";
		mgrequest.Button3 = "";
		mgrequest.Button4 = "";
		mgrequest.DisplayMessage = "";
		mgrequest.X = "";
		mgrequest.Y = "";
		mgrequest.W = "";
		mgrequest.H = "";
		mgrequest.ImagePath = "";
		mgrequest.ImageName = "";
		mgrequest.HRefNum = "";
		mgrequest.Upload = 0;

		if (isUploadSignatureCapture) {
			mgrequest.Upload = isUploadSignatureCapture ? 1 : 0;
			mgrequest.HRefNum = mPaymentRequest.HostCode;
		}

	}

	private String getExtrDate(){
		String extData = "";
		
		if (mPaymentRequest.PayType == PaymentType.CREDIT_CARD) {
			if (isSignatureCapture ) {
				if (PayAmt >= SignMinAmt) {
					extData += "<SignatureCapture>1</SignatureCapture>";
					if (isUploadSignatureCapture) {
						extData += "<SignUploadFlag>1</SignUploadFlag>";
					}
				}
			}
		}
		
		if (isForce) {
			extData += "<Force>T</Force>";
		}
		
		return extData;
	}
	
	private void setPaymentRequest(PaymentRequest payrequest) {
		payrequest.TenderType = payrequest.ParseTenderType(ParsePaymentType(mPaymentRequest.PayType));
		payrequest.TransType = payrequest.ParseTransType(ParseTransactionType(mPaymentRequest.TransType));
		payrequest.ECRRefNum = mPaymentRequest.refNum;
		payrequest.Amount = mPaymentRequest.paymentAmount;

		payrequest.ExtData = getExtrDate();

	}

	private void setPaymentResponse(PaymentResponse response) {
		mPaymentResponse.ResultType = parseResponse(response.ResultCode, response.ResultTxt);
		mPaymentResponse.ResultCode = response.ResultCode;
		mPaymentResponse.ResultTxt = response.ResultTxt;
		mPaymentResponse.Message = response.Message;
		
		mPaymentResponse.AuthCode = response.AuthCode;
		mPaymentResponse.CardType = response.CardType;
		mPaymentResponse.RefNum = response.RefNum;
		mPaymentResponse.BogusAccountNum = response.BogusAccountNum;
		mPaymentResponse.ExtData = response.ExtData ;
		
		SignStatusNum = -1;
		if (!mPaymentResponse.ExtData.equals("")) {
			String num = StringUtils.getTagValue(mPaymentResponse.ExtData, "SignStatusNum");  
			if (num.toString().equals("")) {
				SignStatusNum = -1;
			}else{
				SignStatusNum = Integer.valueOf(num);
			}
		}
		
	}

	@Override
	public void initialize() {
		
		InitializePinPad init = new InitializePinPad();
		Thread initThread = new Thread(init);
		initThread.start();
	}

	
	
	public class InitializePinPad implements Runnable{
		
		@Override
		public void run() {
//			mPaymentRequest.ActionType = PaxPinPad.MGR_TRANS_SETVAR;
			ManageRequest mgrequest = new ManageRequest();

//			setManageRequest(mgrequest);
			
			mgrequest.TransType = mgrequest.ParseTransType("SETVAR");
			mgrequest.EDCType = mgrequest.ParseEDCType("ALL") ;
			mgrequest.VarName = "hostRspTimeout";
			mgrequest.VarValue = "0";
			mgrequest.Title = "";
			mgrequest.Button1 = "";
			mgrequest.Button2 = "";
			mgrequest.Button3 = "";
			mgrequest.Button4 = "";
			mgrequest.DisplayMessage = "";
			mgrequest.X = "";
			mgrequest.Y = "";
			mgrequest.W = "";
			mgrequest.H = "";
			mgrequest.ImagePath = "";
			mgrequest.ImageName = "";
			mgrequest.HRefNum = "";
			mgrequest.Upload = 0;
			mgrequest.TimeOut ="900";
			mgrequest.HRefNum = "";
			

			PosLink  poslink = new PosLink();
			poslink.appDataFolder = mAppDataFolder;
			poslink.PaymentRequest = null;
			poslink.ManageRequest = mgrequest;
//			ProcessTransResult ptr = poslink.ProcessTrans();
			poslink.ProcessTrans();
		}
		
	}



	
}
